import CryptoJS from 'crypto-js';

const SALT = 'aishoo0eex7iTheeb8ieGae8lo5piequ'; // 密钥
const IV = '1234567812345678'; // 十六位十六进制数作为密钥偏移量

const getAesString = (data: string, key: string, iv: string): string => {
  const key1 = CryptoJS.enc.Utf8.parse(key);
  const iv1 = CryptoJS.enc.Utf8.parse(iv);
  const encrypted = CryptoJS.AES.encrypt(data, key1, {
    iv: iv1,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });
  return encrypted.toString(); // 返回的是base64格式的密文
};

export const getAES = (data: string): string => {
  const key = SALT;
  const iv = IV;
  const encrypted = getAesString(data, key, iv); // 密文
  return encrypted;
};

const getDAesString = (encrypted: string, key: string, iv: string): string => {
  const key1 = CryptoJS.enc.Utf8.parse(key);
  const iv1 = CryptoJS.enc.Utf8.parse(iv);
  const decrypted = CryptoJS.AES.decrypt(encrypted, key1, {
    iv: iv1,
    mode: CryptoJS.mode.CBC,
    padding: CryptoJS.pad.Pkcs7
  });
  return decrypted.toString(CryptoJS.enc.Utf8);
};

export const getDAes = (data: string): string => {
  const key = SALT;
  const iv = IV;
  const decryptedStr = getDAesString(data, key, iv);
  return decryptedStr;
};
